<template>
  <base-breadcrumb>
    <searchData
      ref="searchDataRef"
      :search-data="searchArr"
      @search="search"
    />
    <a-card
      :bordered="false"
      style="over-flow: scroll"
    >
      <div>
        <a-row>
          <a-col
            :md="24"
            :sm="19"
          >
            <!-- <a-button
              v-btnPermission="'stm_003_add_01'"
              class="mb12"
              icon="plus"
              type="primary"
              @click="handleAdd('add')"
            >
              添加科技管理策划
            </a-button> -->
            <a-collapse
              v-model="activeKey"
              :bordered="false"
              expand-icon-position="right"
              class="mb12"
            >
              <a-collapse-panel
                style="background: #e6f3fc; border: none"
                :show-arrow="false"
              >
              <a-button type="primary" v-btnPermission="'stm_003_exp_09'" @click="exportCountPlotsFn" style="margin-bottom:10px">导出</a-button>
              <div>
              </div>
                <template slot="header">
                  <a-row
                    type="flex"
                    justify="space-between"
                    align="middle"
                    style="width: 100%"
                  >
                    <div>
                      <a-icon
                        style="color: #108ee9"
                        type="exclamation-circle"
                      />
                      <span
                        class="btn_right"
                      >已选择 <a>{{ selectedRowKeys.length }}</a> 项</span><span class="btn_right">总计：策划成果数：{{ simple.plotsCompleteNum || 0 }}</span><span class="btn_right">获得成果数：{{ simple.completeNum || 0 }}</span><span
                        class="btn_right"
                      >策划完成率：{{
                        simple.completionRate ? (simple.completionRate * 100).toFixed(2) + '%' : '0%'
                      }}</span>
                    </div>
                    <div>
                      <a-button
                        :loading="loading"
                        :disabled="!selectedRowKeys.length"
                        class="btn_right"
                        type="primary"
                        @click.stop="getCollect"
                      >
                        汇总选中
                      </a-button>
                      <a class="btn_right">
                        <span>{{ activeKey.length > 0 ? '收起' : '展开' }}详细汇总信息</span>
                        <a-icon :type="activeKey.length > 0 ? 'up' : 'down'" />
                      </a>
                    </div>
                  </a-row>
                </template>
                <div>
                  <s-table
                    ref="tableSummary"
                    table-layout="fixed"
                    size="default"
                    row-key="id"
                    :columns="columnsTotal"
                    :data="loadDataSummary"
                    bordered
                    :alert="true"
                    show-size-changer
                    show-quick-jumper
                    :show-pagination="false"
                    style="background: #fff"
                  />
                </div>
              </a-collapse-panel>
            </a-collapse>
            <!-- <a-alert :showIcon="true">
            <template slot="message">
              <a-row type="flex" justify="space-between">
                <a-col>
                <span class="btn_right">已选择 <a>{{ selectedRowKeys.length }}</a> 项</span><span class="btn_right">总计：策划成果数：{{plotArchiveNum || 0 }}</span><span class="btn_right">获得成果数：{{getNum || 0 }}</span><span class="btn_right">策划完成率：{{completionRate || '0%' }}</span>
                </a-col>
                <a-col>
                  <a-row type="flex" justify="space-between">
                    <a-button :disabled="!selectedRowKeys.length" class="btn_right" @click="getCollect" size="small" type="primary">汇总选中</a-button>
                    <modal :selectProjectId="selectProjectId"></modal>
                  </a-row>
                </a-col>
              </a-row>
            </template>
          </a-alert> -->
          <!-- :row-selection="rowSelection" -->
            <list-table
              ref="table"
              tableLayout="fixed"
              size="default"
              row-key="poltId"
              :columns="columns"
              :startIndex="0"
              :request="loadData"
              :alert="true"
              show-size-changer
              show-quick-jumper
              show-pagination="auto"
              :row-selection="rowSelection"
              :is-show-count-bar="false"
              :export-config="{ use: true, select: '科技管理策划', all: '科技管理策划', customColumns: customColumns }"
              @exportSelect="exportExcel"
              @exportAll="exportExcel"
            >
              <template slot="version" slot-scope="text, record">
                <a @click="toUpdate(record.versionVOS)">
                  V{{ record.versionVOS.length + 1 }}
                </a>
              </template>
              <span
                slot="action"
                slot-scope="text, record"
              >
                <MoreButton>
                  <a v-btnPermission="'stm_003_loo_02'" @click="handleSub(record, 'view')">查看</a>
                  <a
                    v-btnPermission="'stm_003_edi_03'"
                    v-if="(record.plotsStatusCode == 0 || record.plotsStatusCode == 3)&&hideBuquBtn()"
                    @click="handleSub(record, 'edit')"
                  >编辑</a>
                  <a
                    v-if="record.plotsStatusCode == 2&&hideBuquBtn()"
                    @click="handleSub(record, 'update')"
                  >更新</a>
                  <!-- 当状态为审批中 -->
                  <template v-if="record.plotsStatusCode != '0'">
                    <a @click="$bus.$emit('showApprovalDetailsDialog', record.poltId)">审批详情</a>
                  </template>
                </MoreButton>
              </span>
              <div
                slot="expandedRowRender"
                slot-scope="record"
              >
                <p
                  v-for="item in record.plotAchievements"
                  :key="item.id"
                >
                  <span class="mr20">{{ item.typeName }}</span>
                  <span class="mr20">{{ item.levelName }}</span>
                  <span class="mr20">策划数量：{{ item.plotNum || 0 }}</span>
                  <span class="mr20">获得成果数量：{{ item.getNum || 0 }}</span>
                  <span>完成率：{{ item.completionRate ? (item.completionRate * 100).toFixed(2) + '%' : 0 }}</span>
                </p>
                <span v-if="!record.plotAchievements || record.plotAchievements.length < 1">
                  暂无信息
                </span>
              </div>
            </list-table>
          </a-col>
        </a-row>
      </div>
    </a-card>

    <version
      :visible.sync="versionVisible"
      :list="curList"
    ></version>
  </base-breadcrumb>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getSciencePlots, getPlotsCollect,exportCountPlots } from '@/api/science'
import { getOrgTree } from '@/api/commons'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import OrgTreeSelect from '@/components/OrgTreeSelect'
import ARow from 'ant-design-vue/es/grid/Row'
import version from './versionmodal.vue'
import { Collapse } from 'ant-design-vue' // ant
import Excel from 'exceljs'

const columns = [
  // {
  //   title: '序号',
  //   scopedSlots: { customRender: 'serial' }
  // },
  {
    title: '项目名称',
    ellipsis: true,
    width: '150px',
    dataIndex: 'projectName',
  },
  {
    title: '项目科技管理类别',
    width: '100px',
    dataIndex: 'cate',
  },
  {
    title: '所属分公司',
    ellipsis: true,
    width: '150px',
    dataIndex: 'branchCompany',
  },
  {
    title: '策划成果数',
    ellipsis: true,
    width: '110px',
    dataIndex: 'plotNum',
  },
  {
    title: '获得成果数',
    ellipsis: true,
    width: '110px',
    dataIndex: 'getNum',
  },
  {
    title: '策划完成率',
    dataIndex: 'plotCompletionRate',
    ellipsis: true,
    width: '110px',
    customRender: (value, row) => {
      return (Number(row.plotCompletionRate) * 100).toFixed(2) + '%'
    },
  },
  {
    title: '计划开竣工日期 ',
    ellipsis: true,
    width: '200px',
    dataIndex: 'dateTime',
    customRender: (value, row) => {
      return row.dateTime =  row.startDate && row.endDate ? row.startDate + '至' + row.endDate : '暂无'
    },
  },
  {
    title: '项目立项日期 ',
    width: '120px',
    dataIndex: 'approvalDate',
  },
  {
    title: '首次审批通过日期 ',
    width: '120px',
    dataIndex: 'firstDate',
  },
  {
    title: '版本',
    dataIndex: 'version',
    width: '100px',
    scopedSlots: { customRender: 'version' }
  },
  {
    title: '状态 ',
    width: '120px',
    dataIndex: 'plotsStatus',
    // dataIndex: 'completeStatus',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    fixed: 'right',
    scopedSlots: { customRender: 'action' },
  },
]
const searchArr = [
  // 搜索框
  {
    name: '所属单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
  },
  // {
  //   name: '所属分公司',
  //   valueKey: 'branchCompanyId',
  //   placeholder: '请选择',
  //   type: SelectSubCompany,
  // },
  // {
  //   name: '项目名称',
  //   placeholder: '请选择',
  //   valueKey: 'projectId',
  //   type: SelectProject,
  // },
  // {
  //   name: '项目名称',
  //   value: 'achievementsName',
  //   type: 'input',
  // },
  // {
  //   name: '所属分公司',
  //   value: 'orgName',
  //   type: 'input',
  // },
  {
    name: '计划开竣工日期',
    value: 'constructionDate',
    type: 'dateRange',
  },
]
const renderContent = (value, row, index) => {
  const obj = {
    children: value,
    attrs: {},
  }
  if (index === 4) {
    obj.attrs.colSpan = 0
  }
  return obj
}

const data = [
  {
    key: '1',
    name: 'John Brown',
    age: 32,
    tel: '0571-22098909',
    phone: 18889898989,
    address: 'New York No. 1 Lake Park',
  },
  {
    key: '2',
    name: 'Jim Green',
    tel: '0571-22098333',
    phone: 18889898888,
    age: 42,
    address: 'London No. 1 Lake Park',
  },
  {
    key: '3',
    name: 'Joe Black',
    age: 32,
    tel: '0575-22098909',
    phone: 18900010002,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: '4',
    name: 'Jim Red',
    age: 18,
    tel: '0575-22098909',
    phone: 18900010002,
    address: 'London No. 2 Lake Park',
  },
  {
    key: '5',
    name: 'Jake White',
    age: 18,
    tel: '0575-22098909',
    phone: 18900010002,
    address: 'Dublin No. 2 Lake Park',
  },
]

export default {
  name:'a'+ Date.now(),
  components: {
    ARow,
    STable,
    // Add: 'add-post',
    ACollapse: Collapse,
    ACollapsePanel: Collapse['Panel'],
    version
  },
  data() {
    const columnss = [
      {
        title: 'Name',
        dataIndex: 'name',
        customRender: (value, row, index) => {
          const obj = {
            children: value,
            attrs: {},
          }
          if (index === 2) {
            obj.attrs.rowSpan = 2
          }
          // These two are merged into above cell
          if (index === 3) {
            obj.attrs.rowSpan = 0
          }
          if (index === 4) {
            obj.attrs.colSpan = 0
          }
          return obj
        },
      },
      {
        title: 'Age',
        dataIndex: 'age',
        customRender: renderContent,
      },
      {
        title: 'Home phone',
        colSpan: 2,
        dataIndex: 'tel',
        customRender: (value, row, index) => {
          const obj = {
            children: value,
            attrs: {},
          }
          if (index === 2) {
            obj.attrs.rowSpan = 2
          }
          // These two are merged into above cell
          if (index === 3) {
            obj.attrs.rowSpan = 0
          }
          if (index === 4) {
            obj.attrs.colSpan = 0
          }
          return obj
        },
      },
      {
        title: 'Phone',
        colSpan: 0,
        dataIndex: 'phone',
        customRender: renderContent,
      },
      {
        title: 'Address',
        dataIndex: 'address',
        customRender: renderContent,
      },
    ]
    this.columns = columns
    const columnsTotal = [
      {
        title: '分公司名称',
        dataIndex: 'name',
        customRender: (text, row, index) => {
          // this.$nextTick(() => {
          let rowSpan = 1
          if (index != 0 && text === this.simple.plotsCountTable[index - 1].name) {
            rowSpan = 0
            // 若不是，则往下合并与改行考核内容一致行的总行数
          } else {
            rowSpan = [...this.simple.plotsCountTable].filter((i) => i.name == text).length
          }
          return {
            children: text,
            attrs: {
              rowSpan: rowSpan,
            },
          }
          // })
        },
      },
      {
        title: '成果分类',
        dataIndex: 'typeName',
        customRender: (text, row, index) => {
          // this.$nextTick(() => {
          let rowSpan = 1
          if (
            index != 0 &&
            text === this.simple.plotsCountTable[index - 1].typeName &&
            row.name === this.simple.plotsCountTable[index - 1].name
          ) {
            rowSpan = 0
            // 若不是，则往下合并与改行考核内容一致行的总行数
          } else {
            rowSpan = [...this.simple.plotsCountTable].filter((i) => i.typeName == text && row.name === i.name).length
          }
          return {
            children: text,
            attrs: {
              rowSpan: rowSpan,
            },
          }
          // })
        },
      },
      {
        title: '成果等级',
        dataIndex: 'levelName',
      },
      {
        title: '策划数量',
        dataIndex: 'plotsCompleteNum',
      },
      {
        title: '获得成果数量',
        dataIndex: 'completeNum',
      },
      {
        title: '策划完成率',
        dataIndex: 'completeRate',
        customRender: (e) => {
          return (e * 100).toFixed(2) + '%'
        },
      },
    ]
    this.columnsTotal = columnsTotal
    return {
      versionVisible: false,
      args: {
        countTableType: '1',
        ids: [], // 表格选中集合
      },
      searchArr,
      visible: false,
      confirmLoading: false,
      contentList: {
        tab1: 'content1',
        tab2: 'content2',
      },
      activeKey: [],
      key: 'tab1',
      groupAdd: false,
      data,
      columnss,
      employeeName: '',
      editForm: {
        status: '1',
      },
      form: {
        expetGroupName: '',
        remarks: '',
      },
      companyList: [],
      advanced: false,
      mdl: null,
      // 查询参数
      queryParam: {},
      loading: false,
      simple: {},
      init: false,
      loadDataSummary: () => {
        if (!this.selectProjectId.length) {
          return false
        }
        this.loading = true
        return getPlotsCollect({ projectIds: this.selectProjectId.join(), projects: this.selectProjects.join() })
          .then((res) => {
            this.loading = false
            if (res.code === 200) {
              this.simple = res.data
              let datas = {
                data: res.data.plotsCountTable,
              }
              return datas
            } else {
              return false
            }
          })
          .catch((res) => {
            this.loading = false
          })
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        if (this.queryParam.constructionDate && this.queryParam.constructionDate.length > 0) {
          this.queryParam.constructionDateStart = this.queryParam.constructionDate[0].format('YYYY-MM-DD')+ ' 00:00:00'
          this.queryParam.constructionDateEnd = this.queryParam.constructionDate[1].format('YYYY-MM-DD')+ ' 23:59:59'
          delete this.queryParam.constructionDate
        }
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getSciencePlots(requestParameters).then((res) => {
          this.$refs.table.clearSelected()
          return res
        })
      },
      expertList: {},
      selectedRowKeys: [],
      selectedRows: [],
      selectorgId: [],
      selectconstructionDate: [],
      selectProjectId: [],
      selectProjects: [],
      plotArchiveNum: '',
      completionRate: '',
      getNum: '',
      showTotal: false,
      curList: [],
      customColumns:[
        {
          header: '项目名称',
          width: 30,
          key: 'projectName',
        },
        {
          header: '项目科技管理类别',
          width: 30,
          key: 'cate',
        },
        {
          header: '所属分公司',
          width: 30,
          key: 'branchCompany',
        },
        {
          header: '策划成果数',
          width: 30,
          key: 'plotNum',
        },
        {
          header: '获得成果数',
          width: 30,
          key: 'getNum',
        },
        {
          header: '策划完成率',
          key: 'CompletionRate',
          width: 30,
        },
        {
          header: '计划开竣工日期 ',
          width: 30,
          key: 'dateTime',
        },
        {
          header: '项目立项日期 ',
          width: 30,
          key: 'approvalDate',
        },
        {
          header: '首次审批通过日期 ',
          width: 30,
          key: 'firstDate',
        },
        {
          header: '版本',
          key: 'version',
          width: 30,
        },
        {
          header: '状态 ',
          width: 30,
          key: 'plotsStatus',
        },
],//需要导出的字段
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange,
      }
    },
  },
  created() {
    this.customColumns = this.customColumns.filter(item=>{
      return item.title !== '操作'
    })
  },
  methods: {
    // 导出
    async exportExcel(data) {
      const wb = new Excel.Workbook()
      const sheet = wb.addWorksheet('Sheet1')
      sheet.columns = this.customColumns
      data.forEach(item => {
        item.dateTime = item.startDate && item.endDate ? item.startDate + '至' + item.endDate : '暂无';
        item.version =  `V${item.versionVOS.length + 1 }`;
        item.CompletionRate = (Number(item.plotCompletionRate) * 100).toFixed(2) + '%';
      })
      sheet.addRows(data)
      sheet.getRow(1).font = { name: '等线', bold: true }
      // 导出
      const buffer = await wb.xlsx.writeBuffer()
      let blob = new Blob([buffer], {
        type: 'application/octet-stream'
      })

      let url = blob
      if (url instanceof Object && url instanceof Blob) {
        url = URL.createObjectURL(url) // 创建blob地址
      }
      var aLink = document.createElement('a')
      aLink.href = url
      aLink.download = '科技管理策划.xlsx' // 文件名
      let event
      if (window.MouseEvent) {
        event = new MouseEvent('click')
      } else {
        event = document.createEvent('MouseEvents')
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      }
      aLink.dispatchEvent(event)
    },
    /** 
     * 汇总导出
     * @param parameter
     */
    async exportCountPlotsFn(){
      // let param = this.$refs.searchDataRef.form.getFieldsValue();
      let res = await exportCountPlots({ projectIds: this.selectProjectId.join(), projects: this.selectProjects.join() });
      this.handleDownload(res)
    },
    /**
     * 转义下载
     * @param parameter
     */
    handleDownload(res){
      console.log('res.data',res.data)
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename.substring(filename.indexOf("''") + 2) // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
    showModal() {
      this.visible = true
    },
    onChange() {},
    onTabChange(key, type) {
      console.log(key, type)
      this[type] = key
    },
    handleAdd(type) {
      this.$router.push({
        name: '/science/plots/addPlots',
        query: {
          type: type,
        },
      })
    },
    getCollect() {
      if (this.activeKey.length === 0) {
        this.activeKey = ['0']
        if (this.init) {
          this.$nextTick(() => {
            this.$refs.tableSummary.refresh(true)
          })
        } else {
          this.init = true
        }
      } else {
        this.$nextTick(() => {
          this.$refs.tableSummary.refresh(true)
        })
      }
    },
    onChangeTime(value) {
      let year = value.constructionDate._d.getFullYear()
      let month = value.constructionDate._d.getMonth() + 1
      let date = value.constructionDate._d.getDate()
      this.queryParam.constructionDate = year + '-' + month + '-' + date
    },
    onSearch(value) {
      console.log(value)
    },
    // showModal() {
    //   this.visible = true
    //   this.getOrgTree()
    // },
    handleOk(e) {
      this.confirmLoading = true
      setTimeout(() => {
        this.visible = false
        this.confirmLoading = false
      }, 2000)
    },
    search(values) {
      this.queryParam = values

      this.$refs.table.refresh(true)
    },
    handleCancel(e) {
      this.visible = false
    },
    handleEdit(record) {
      this.$router.push({ name: '/science/plots/addPlots', query: { id: record.poltId, type: 'add' } })
    },
    handleCancelGroup() {
      this.groupAdd = false
    },
    handleSub(record, type) {
      if (type == 'edit' && (!record.cate)) {
        this.$message.error('该项目暂无科技管理类别信息，请到项目列表设置管理科技类别')
        return
      }
      this.$router.push({ name: '/science/plots/addPlots', query: { id: record.poltId, type: type } })
    },
    toUpdate(list) {
      this.curList = list
      this.versionVisible = true
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.selectorgId = []
      this.selectProjectId = []
      this.selectProjects = []
      this.selectconstructionDate = []
      this.selectedRows.forEach((item) => {
        this.selectProjectId.push(item.projectInfoId)
        this.selectProjects.push(item.projectId)
      })
      let selectedRowsMap = new Map()
      selectedRowsMap.set(this.$refs.table.pageNo, selectedRows)
      this.$refs.table.selectedRowKeys = this.selectedRowKeys
      this.$refs.table.selectedRowsMap = selectedRowsMap
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    // getOrgTree() {
    //   getOrgTree().then((res) => {
    //     this.companyList = res.data
    //   })
    // },
    onSelect(selectedKeys, info) {
      console.log(info.selectedNodes[0].data.props.id)
      let id = info.selectedNodes[0].data.props.id
      getExpertGroupExcept({ orgId: id, status: 1 }).then((res) => {
        console.log('不是专家组人员：' + res)
      })
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
  },
}
</script>
<style lang="less" scoped>
  /deep/.ant-alert-info {
    // display: none;
  }
.sprite {
  background-color: #f2f2f2;
  height: 550px;
  width: 1px;
}
.item {
  background-color: #f2f2f2;
  height: 400px;
  width: 180px;
  padding: 10px;
}
.sideItem {
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #fff;
  text-align: center;
  cursor: pointer;
}
.sideItem:hover {
  background: #aaa;
}
.input {
  border-radius: 10px;
}
.font {
  font-weight: bold;
}
.expert {
  background-color: #eee;
  height: 300px;
  padding: 10px;
  text-align: center;
}
.selects {
  background-color: #e6f3fc;
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-color: #d4f0fc;
  border-radius: 4px;
  -moz-box-shadow: none;
  -webkit-box-shadow: none;
  box-shadow: none;
  text-align: left;
  line-height: 24px;
  padding: 5px 10px;
  vertical-align: middle;
}

</style>